/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import rentaldb.Tenant;

/**
 *
 * @author Pop
 */
public class TenantDao {
    private EntityManager em;
    private EntityManagerFactory emf;
    
    public TenantDao(){
        try{
            emf = Persistence.createEntityManagerFactory("RentaldbPU");
            em = emf.createEntityManager();  
        }catch(Exception e){ System.out.println(e);}
    }
    
    public void persist(Tenant t){
        em.getTransaction().begin();
        em.persist(t);
        em.getTransaction().commit();
        
    }
    
    public void update(Tenant t){
        em.getTransaction().begin();
        em.merge(t);
        em.getTransaction().commit();
    }
    
    public void delete(Tenant t) throws Exception{
        t = getTenantById(t.getTenantId());
        em.getTransaction().begin();
        em.remove(t);
        em.getTransaction().commit();
    }
    
    public Tenant getTenantById(Integer id) throws Exception{
        //em.createQuery("select * from property");
        Query q = em.createNamedQuery("Tenant.findByTenantId");
        q.setParameter("tenantId", id);
        Tenant t = (Tenant)q.getSingleResult();
        
        return t;
    }
    
    public List<Tenant> getAllTenants() throws Exception{
        Query q = em.createNamedQuery("Tenant.findAll");
        List<Tenant> tenantList = q.getResultList();
        
        return tenantList;
    }
}
